<?php
#### DATABASE CLASS ############################################################
class Database {

	function Database() {
		Base::getThis();
	}

	#### DATABASE CONNECT ######################################################
	function initialise() {
		// Include database class and create new instance
		require_once('includes/database/'.$this->config['db']['type'].'.inc');
		$this->db = new $this->config['db']['type']();

		// Create database connection
		$this->db_connection[1] = $this->db->connect($this->config['db']['host'], $this->config['db']['username'], $this->config['db']['password'], $this->config['db']['name']);

		// Example second database connection
		//$db_connection[2] = $lfdb->connect($config['db']['host2'], $config['db']['username2'], $config['db']['password2'], $config['db']['name2']);
	}

	#### CACHE #####################################################################
	function cache($file, $sql = FALSE, $connection = FALSE, $expire = FALSE) {

		$file = 'cache/'.$file.'.cache';
		if (!isset($this->config['sql_cache_enabled'])) $this->config['sql_cache_enabled'] = TRUE;

		if ($this->config['sql_cache_enabled'] && file_exists($file) && ((filemtime($file) > (time() - $expire)) || $expire == FALSE)) {
			$this->db->sql = NULL;
			include($file);
			$results = unserialize(stripslashes($cache_data));
		} else {
			$this->db->query($sql, $connection) or sql_error(__FILE__, __LINE__);
			$results = $this->db->result();

			if ($this->config['sql_cache_enabled'] && ($expire == FALSE || is_int($expire))) {
				if($fp = fopen($file, 'w')) {
					fputs($fp, "<?php \$cache_data = '".addslashes(serialize($results))."'; ?>");
					fclose($fp);
				} else {
					die('Could not write cache file: '.$file);
				}
			}
		}

		return $results;
	}

	#### GET COMMON TABLES #####################################################
	function getCommonTable() {
		$this->db->select($this->db->table['common']);
		$rows = $this->db->cache('common');
		foreach ($rows as $row) {
			$this->common[$row['name']] = $row['value'];
		}
	}

	#### GET CONFIG TABLE ######################################################
	function getConfigTable() {
		// Prevent config from being cached
		if (!$this->config['cache']['config']) $this->config['sql_cache_enabled'] = FALSE;

		$this->db->select($this->db->table['config']);
		$rows = $this->db->cache('config');
		foreach ($rows as $row) {
			foreach ($row as $key => $value) {
				$this->config[$key] = $value;
			}
		}
	}

}
?>